import 'dart:io';
import 'dart:math';

import 'package:aqua_plunge/constants/colors.dart';
import 'package:aqua_plunge/util/MedalType.dart';
import 'package:aqua_plunge/widget/app_bar.dart';
import 'package:flutter/material.dart';
import 'package:flutter_staggered_grid_view/flutter_staggered_grid_view.dart';
import 'package:flutter_util_code/utils.dart';
import 'package:get/get.dart';
import 'package:image_picker/image_picker.dart';
import 'package:path_provider/path_provider.dart';

import '../controller/DatabaseListController.dart';
import '../http/app_manager.dart';
import '../model/Creation.dart';
import '../services/database_service.dart';

class PostPage extends StatefulWidget {
  const PostPage({super.key});

  @override
  State<PostPage> createState() => _PostPageState();
}

class _PostPageState extends State<PostPage> {
  final DatabaseService _databaseService = DatabaseService.instance;
  final ImagePicker _picker = ImagePicker();
  final List<XFile> _images = [];

  late TextEditingController _titleController;
  late TextEditingController _describeController;

  MedalType? _medalType;

  final DatabaseController _databaseController = Get.find<DatabaseController>();

  get _contentView => Container(
        padding: const EdgeInsets.all(24),
        child: Column(children: [
          TextField(
            controller: _titleController,
            maxLength: 100,
            decoration: const InputDecoration(
                counterText: "",
                hintText: "Type your title",
                hintStyle: TextStyle(color: AppColors.hintColor, fontSize: 18),
                focusedBorder: UnderlineInputBorder(
                    borderSide: BorderSide(color: Colors.white)),
                enabledBorder: UnderlineInputBorder(
                    borderSide: BorderSide(color: Colors.white))),
            style: const TextStyle(color: Colors.white, fontSize: 18),
          ),
          TextField(
            maxLines: null,
            controller: _describeController,
            maxLength: 500,
            decoration: const InputDecoration(
                hintText: "Start your creation...",
                counterStyle: TextStyle(color: AppColors.hintColor),
                hintStyle: TextStyle(color: AppColors.hintColor, fontSize: 18),
                border: InputBorder.none),
            style: const TextStyle(color: Colors.white, fontSize: 14),
          ),
          const SizedBox(height: 44),
          _gridview,
          GestureDetector(
            onTap: () {
              _postPublish();
            },
            child: Image.asset('images/icon_btn_post.png'),
          ),
          const SizedBox(height: 20)
        ]),
      );

  get _gridview => _buildGrid();

  Future<void> _addPicture() async {
    final status = await Permission.photos.request();
    if (status.isGranted) {
      final pickedFile = await _picker.pickImage(source: ImageSource.gallery);
      setState(() {
        if (pickedFile != null) {
          _images.add(pickedFile);
        }
      });
    }
  }

  Widget _buildGrid() {
    return Flexible(
        child: MasonryGridView.count(
            crossAxisCount: 3,
            itemCount: _images.length + 1,
            crossAxisSpacing: 14,
            mainAxisSpacing: 14,
            itemBuilder: (context, index) {
              if (index == _images.length) {
                return GestureDetector(
                  onTap: () async {
                      _addPicture();
                  },
                  child: Container(
                      width: 100,
                      height: 120,
                      decoration: BoxDecoration(
                          borderRadius: BorderRadius.circular(12),
                          image: const DecorationImage(
                              image: AssetImage('images/icon_add_photo.png'),
                              fit: BoxFit.cover))),
                );
              }
              return _gridviewItem(context, index);
            }));
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: appBar(""),
      body: Stack(
        children: [
          Container(
            decoration: const BoxDecoration(
                image: DecorationImage(
                    image: AssetImage('images/img_primary_bg.png'),
                    fit: BoxFit.fill)),
          ),
          _contentView
        ],
      ),
    );
  }

  @override
  void initState() {
    super.initState();
    _titleController = TextEditingController();
    _describeController = TextEditingController();
    getArguments();
  }

  getArguments() {
    _medalType = Get.rawRoute?.settings.arguments == null
        ? MedalType.level1
        : Get.rawRoute?.settings.arguments as MedalType;
  }

  @override
  void dispose() {
    super.dispose();
    _titleController.dispose();
    _describeController.dispose();
  }

  Widget _gridviewItem(BuildContext count, int index) {
    return Container(
      width: 100,
      height: 120,
      decoration: BoxDecoration(
          borderRadius: BorderRadius.circular(12),
          image: DecorationImage(
              image: Image.file(File(_images[index].path)).image,
              fit: BoxFit.cover)),
      child: Container(
        alignment: Alignment.topRight,
        padding: const EdgeInsets.only(top: 4, right: 6),
        child: Stack(
          children: [
            GestureDetector(
              onTap: () {
                setState(() {
                  _images.removeAt(index);
                });
              },
              child:
                  Image.asset('images/icon_delete.png', width: 20, height: 20),
            )
          ],
        ),
      ),
    );
  }

  void _postPublish() async {
    if (_titleController.text.isEmpty ||
        _describeController.text.isEmpty ||
        _images.isEmpty) {
      ScaffoldMessenger.of(context).showSnackBar(const SnackBar(
        content: Text('You still have information to fill in'),
        duration: Duration(milliseconds: 2500),
      ));
    } else {
      _databaseService.addCreation(Creation(
        userId: int.parse(AppManager.getUserInfo().userId!),
        postId: Random().nextInt(100000) + 100000,
        title: _titleController.text,
        describe: _describeController.text,
        cover: _images.first.path,
        content: _images.map((file) => file.path).toList(),
      ));
      if (_medalType != null) {
        AppManager.getMedal(_medalType!);
      }
      _databaseController.fetchMineData();
      Get.back(result: true);
    }
  }

  Future<String?> get _localPath async {
    final directory = await getApplicationDocumentsDirectory();
    return directory.path;
  }

  Future<void> _createDirectory(String path) async {
    final directory = Directory(path);
    await directory.create(recursive: true);
  }

  Future<bool> _checkDirectoryExists(String path) async {
    final directory = Directory(path);
    return await directory.exists();
  }

  Future<void> copyImageToProjectDirectory(XFile imageFile) async {
    try {
      final localPath = await _localPath;
      final imagePath = '$localPath/images/';
      final fileName = imageFile.name;
      final targetPath = '$imagePath$fileName';

      if (!await _checkDirectoryExists(imagePath)) {
        await _createDirectory(imagePath);
      }
      await File(imageFile.path).copy(targetPath);
      debugPrint('=====targetpath:$targetPath');
    } catch (error) {
      debugPrint('Error copying file: $error');
    }
  }
}

class PostChangeEvent {
  final MedalType medalType;

  PostChangeEvent(this.medalType);
}
